import amqp from 'amqplib';

export const receiveMessages = async (userId: string, callback: (message: string) => void) => {
  try {
    console.log('userId===>>>', userId)
    const connection = await amqp.connect('amqp://localhost:5672').catch(err => {
      console.error('RabbitMQ 连接错误详情:', err);
      throw err;
    });

    console.log('connection 成功');
    const channel = await connection.createChannel().catch(err => {
      console.error('RabbitMQ 创建通道错误:', err);
      throw err;
    });

    console.log('创建消息队列');
    const EXCHANGE_NAME = 'bi_frontend_exchange';
    const queueName = `bi_frontend_queue_${userId}`;
    const ROUTING_KEY = `bi_frontend_routing_key_${userId}`;

    console.log('连接到队列:', queueName);

    // 设置消费者
    await channel.consume(queueName, (msg) => {
      if (msg) {
        const messageContent = msg.content.toString();
        console.log('收到消息:', messageContent);
        callback(messageContent);
        channel.ack(msg);
      }
    }, {
      noAck: false
    });

    // 添加错误处理
    connection.on('error', (err) => {
      console.error('RabbitMQ 连接错误:', err);
    });

    channel.on('error', (err) => {
      console.error('RabbitMQ 通道错误:', err);
    });

  } catch (error) {
    console.error('RabbitMQ 连接失败:', error);
  }
};
